﻿using sMES_Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sMES_Base.service;
using System.Data;

namespace load_applied_acc_to_machine_process
{
    /// <summary>
	/// 元件[load_applied_acc_to_machine_process]
    /// <auth>JingHuang</auth><time>2018/12/30 下午 05:28:15</time>
    /// <description></description>
    /// <list>
    ///     <modify>
    ///         <auth></auth><mantis>0053952</mantis><time></time>
    ///         <description>設備放上模具</description>
    ///     </modify>
    /// </list>
    /// </summary>
    public class load_applied_acc_to_machine_process_utility : BaseUtility
    {
        public load_applied_acc_to_machine_process_utility(ref BaseService CurrentService) : base(ref CurrentService)
        {
        }

        /// <summary>
        /// 模具上到設備上
        /// </summary>
        /// <returns></returns>
        public bool applied_acc_to_machine_process(RequestContent content, ref string message)
        {
            bool OutData = false;
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmsaccstateCombineACCNo = new DataTable();
            bool is_auto_inout = get_auto_inout_val();
            // 先檢核所有的資料
            // 設備編號 設備類別 模具編號 模具類別 都不允許為空
            foreach (CDO_RequestContent_detail _CDO_RequestContent_detail in content.pTable)
            {
                //if (string.IsNullOrEmpty(_CDO_RequestContent_detail.ACCESSORYNO))
                //    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("ACCESSORYNO") + package_err("IS EMPTY"));

                if (string.IsNullOrEmpty(_CDO_RequestContent_detail.ACCESSORYTYPE))
                    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("ACCESSORYTYPE") + package_err("IS EMPTY"));

                if (string.IsNullOrEmpty(_CDO_RequestContent_detail.EQUIPMENTNO))
                    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("EQUIPMENTNO") + package_err("IS EMPTY"));

                if (string.IsNullOrEmpty(_CDO_RequestContent_detail.EQUIPMENTTYPE))
                    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("EQUIPMENTTYPE") + package_err("IS EMPTY"));

                // 20210426 Modify by Zeke for 85272: 模具上模報錯：TBLEMSEQPACCSTATE重覆索引 [金名山]
                if (IsAccSerialStatusChange(_CDO_RequestContent_detail.ACCESSORYNO.Trim(), _CDO_RequestContent_detail.ACCESSORYVERSION.Trim(), _CDO_RequestContent_detail.ACCSERIALNO.Trim()))
                {
                    //當發現ACCSerialNo不一樣時，系統顯示需按下確認的錯誤訊息
                    //『模治具編號：XXXXXXX，模治具類別：XXXXX，[右無傳入]模治具分類：XXXXXX，[左無傳入]
                    //此模治具已經做過其他功能的狀態異動，系統將自動重新讀取畫面模治具資訊!!』，
                    //按下[確認]後，系統重新讀取可上下模的所有模治具資訊，原畫面勾選結果全數清空。
                    
                     throw new ServiceException(ServiceCode.ParamsValidateException, package_err("ACCESSORYNO") + "：" + _CDO_RequestContent_detail.ACCESSORYNO + "，" + package_err("ACCESSORYTYPE") + "：" + _CDO_RequestContent_detail.ACCESSORYTYPE + "，" + package_err("ACC_ALREADY_STATUS_CHANGE") + "，" + package_err("SYSTEM_WILL_RELOAD_PAGE") + "！");
                }
            }
            string now_time = DateTime.Now.ToString("yyyy/MM/dd H:mm:ss");

            //判斷是否自動下模 <- 這個邏輯有問題
            //若原機臺上有模治具則確定後，選擇的模治具上模，原設備上的模治具下模
            //先把此設備上的模具進行下模處理
            if (content.pTable.Count > 0)
            {
                if (content.IsAutoUnload.ToLower().Equals("y"))
                {
                    unload_accessory_from_equipment(content.pTable[0].EQUIPMENTNO, BaseService._ServiceInfo.account,now_time, content.ACLoadTime);
                }
            }

            Dictionary<string, object> _parameters = new Dictionary<string, object>();
            foreach (CDO_RequestContent_detail _CDO_RequestContent_detail in content.pTable)
            {     
                //'寫入tblEMSEQPACCState
                sbSQL.Clear();
                sbSQL.Append("INSERT INTO tblEMSEQPACCState (  EquipmentType, EquipmentNo, AccessoryType,AccessoryNo, AccessoryVersion, UserNo, StartTime )");
                sbSQL.Append("VALUES('" + _CDO_RequestContent_detail.EQUIPMENTTYPE + "','" + _CDO_RequestContent_detail.EQUIPMENTNO +"',");
                sbSQL.Append("'" + _CDO_RequestContent_detail.ACCESSORYTYPE + "',");
                sbSQL.Append("'" + _CDO_RequestContent_detail.ACCESSORYNO + "',");
                sbSQL.Append("'" + _CDO_RequestContent_detail.ACCESSORYVERSION + "',");
                sbSQL.Append("'" + BaseService._ServiceInfo.account + "',");
                sbSQL.Append(" SYSDATE )");

                CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

                //更新模具狀態
                if (is_auto_inout)
                    change_ACC_state_auto_InOut(_CDO_RequestContent_detail.ACCESSORYNO, now_time, content.ACLoadTime);
                else
                    change_ACC_state(_CDO_RequestContent_detail.ACCESSORYNO, now_time, content.ACLoadTime);

                //更新組合模具
                sbSQL.Clear();
                sbSQL.Append(" Select A.CombineACCNo , B.ACCSerialNo , B.AccessoryNo ");
                sbSQL.Append(" From  tblEMSCombineACCState A Left Join  tblEMSAccessoryState  B  ");
                sbSQL.Append(" On A.AccessoryNo = B.AccessoryNo ");
                sbSQL.Append(" Where  1=1 And CombineACCNo = '" + _CDO_RequestContent_detail.ACCESSORYNO + "'");

                dtEmsaccstateCombineACCNo = CurrentService.GetDao().Query(sbSQL.ToString());

                foreach (DataRow _Datarow in dtEmsaccstateCombineACCNo.Rows)
                {
                    if (is_auto_inout)
                        change_ACC_state_auto_InOut(Convert.ToString(_Datarow["AccessoryNo"]), now_time, content.ACLoadTime);
                    else
                        change_ACC_state(Convert.ToString(_Datarow["AccessoryNo"]),now_time, content.ACLoadTime);
                }

                AddContAccessory(_CDO_RequestContent_detail);

                // 20220309 add by 翰鴻 for M#102577：
                #region
                //当手动输入时间 >= 模具上模标准时间时，系统跳出弹窗，提示“即将达到预设上模时间，请加快上模速度或修改预设数据”

                sbSQL.Clear();
                sbSQL.Append("select COALESCE(F.LoadTime, 0)                                                                            ");
                sbSQL.Append("FROM TBLEMSEQPACCSTATE A                                                                                  ");
                sbSQL.Append("LEFT JOIN tblACCChangeTime F ON A.AccessoryNo = F.AccessoryNo AND A.AccessoryVersion = F.AccessoryVersion ");
                sbSQL.Append("where A.EquipmentNo = ? and A.AccessoryNo = ? and A.AccessoryVersion = ?");

                _parameters.Clear();
                _parameters.Add("EquipmentNo", _CDO_RequestContent_detail.EQUIPMENTNO);
                _parameters.Add("AccessoryNo", _CDO_RequestContent_detail.ACCESSORYNO);
                _parameters.Add("AccessoryVersion", _CDO_RequestContent_detail.ACCESSORYVERSION);

                int LoadTime = 0;
                if(CurrentService.GetDao().Query1RecordInt(Convert.ToString(sbSQL), _parameters).HasValue)
                {
                    LoadTime = CurrentService.GetDao().Query1RecordInt(Convert.ToString(sbSQL), _parameters).Value;
                }
                if (content.ACLoadTime >= LoadTime)
                {                    
                    message += this.CurrentService.GetResource("[%Module_ACC.SPEED_UP_ACC_LOAD%]", _CDO_RequestContent_detail.ACCESSORYNO);
                    message += "<br>";
                }
                #endregion

                // 修改模治具上模数量
                sbSQL.Clear();
                sbSQL.Append($@" select count(1) from TBLCUSMoldMoves where AccessoryNo = '{_CDO_RequestContent_detail.ACCESSORYNO}' and AccessoryVersion = '{_CDO_RequestContent_detail.ACCESSORYVERSION}' ");
                if (CurrentService.GetDao().Query1RecordInt(sbSQL.ToString()) > 0)
                {
                    sbSQL.Clear();
                    sbSQL.Append($@" UPDATE TBLCUSMoldMoves
                                     SET HistoryCount = HistoryCount + 1,CurrentMoldUps = CurrentMoldUps + 1
                                     WHERE AccessoryNo = '{_CDO_RequestContent_detail.ACCESSORYNO}' and AccessoryVersion = '{_CDO_RequestContent_detail.ACCESSORYVERSION}' ");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
                else
                {
                    sbSQL.Clear();
                    sbSQL.Append($@" INSERT TBLCUSMoldMoves ( Creator,CreateDate,AccessoryNo,AccessoryVersion,
                                                              HistoryCount,CurrentMoldUps,HistoricalMoldDowns,CurrentMoldDowns,
                                                              repairStatus,FutureUse,modifiedDate) 
                                     VALUES ('{CurrentService.GetServiceInfo().account}',Getdate(),'{_CDO_RequestContent_detail.ACCESSORYNO}','{_CDO_RequestContent_detail.ACCESSORYVERSION}',
                                             1,1,0,0,
                                             null,0,null) ");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
            }

            return OutData;
        }

        /// <summary>
        /// 把設備上的模具進行下模處理
        /// </summary>
        /// <param name="EQUIPMENTNO"></param>
        /// <param name="AccessoryNo"></param>
        /// <param name="defualt_time"></param>
        private void unload_accessory_from_equipment(string EQUIPMENTNO,string AccessoryNo,string defualt_time, int ACLoadTime)
        {
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmseqpstate = new DataTable();
            DataTable dtEmsaccstateCombineACCNo = new DataTable();
            bool is_auto_inout = get_auto_inout_val();
            sbSQL.Clear();
            sbSQL.Append(" Select A.* , B.ACCSERIALNO ,B.Locatorno ");
            sbSQL.Append(" From TBLEMSEQPACCSTATE A Left Join TBLEMSACCESSORYSTATE  B ");
            sbSQL.Append(" On A.ACCESSORYNO = B.ACCESSORYNO Where  1=1");
            sbSQL.Append(" And A.EquipmentNo = '" + EQUIPMENTNO + "'");

            dtEmseqpstate = CurrentService.GetDao().Query(sbSQL.ToString());

            //  '更改 ChangeACCState
            //  '刪除tblEMSEQPACCState
            //  '更新組合模治具下所有模治具
            foreach (DataRow _DataRow in dtEmseqpstate.Rows)
            {
                //  '更改 ChangeACCState
                if (is_auto_inout)
                    change_ACC_state_for_down_auto_InOut(_DataRow, defualt_time, ACLoadTime);
                else
                    change_ACC_state_for_down(_DataRow, defualt_time, ACLoadTime);

                //'刪除tblEMSEQPACCState
                sbSQL.Clear();
                sbSQL.Append(" Delete From tblEMSEQPACCState Where AccessoryNo = '" + _DataRow["AccessoryNo"] + "' And EquipmentNo = '" + EQUIPMENTNO + "'");
                CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

                // 修改模治具下模数量
                sbSQL.Clear();
                sbSQL.Append($@" select count(1) from TBLCUSMoldMoves where AccessoryNo = '{_DataRow["AccessoryNo"]}' and AccessoryVersion = '{_DataRow["ACCESSORYVERSION"]}' ");
                if (CurrentService.GetDao().Query1RecordInt(sbSQL.ToString()) > 0)
                {
                    sbSQL.Clear();
                    sbSQL.Append($@" UPDATE TBLCUSMoldMoves
                                     SET HistoricalMoldDowns = HistoricalMoldDowns + 1,CurrentMoldDowns = CurrentMoldDowns + 1
                                     WHERE AccessoryNo = '{_DataRow["AccessoryNo"]}' and AccessoryVersion = '{_DataRow["ACCESSORYVERSION"]}' ");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
                else
                {
                    sbSQL.Clear();
                    sbSQL.Append($@" INSERT TBLCUSMoldMoves ( Creator,CreateDate,AccessoryNo,AccessoryVersion,
                                                              HistoryCount,CurrentMoldUps,HistoricalMoldDowns,CurrentMoldDowns,
                                                              repairStatus,FutureUse,modifiedDate) 
                                     VALUES ('{CurrentService.GetServiceInfo().account}',Getdate(),'{_DataRow["AccessoryNo"]}','{_DataRow["ACCESSORYVERSION"]}',
                                             0,0,1,1,
                                             null,0,null) ");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }


                //'更新組合模治具下所有模治具
                sbSQL.Clear();
                sbSQL.Append(" Select A.CombineACCNo , B.ACCSerialNo , B.AccessoryNo ");
                sbSQL.Append(" From  tblEMSCombineACCState A Left Join  tblEMSAccessoryState  B  ");
                sbSQL.Append(" On A.AccessoryNo = B.AccessoryNo ");
                sbSQL.Append(" Where  1=1 And CombineACCNo = '" + _DataRow["AccessoryNo"] + "'");

                dtEmsaccstateCombineACCNo = CurrentService.GetDao().Query(sbSQL.ToString());

                foreach (DataRow _Datarow in dtEmsaccstateCombineACCNo.Rows)
                {
                    if (is_auto_inout)
                        change_ACC_state_for_down_auto_InOut(_DataRow, defualt_time, ACLoadTime);
                    else
                        change_ACC_state_for_down(_DataRow, defualt_time, ACLoadTime);
                }

                // 更新 TBLWIPCONT_ACCESSORY 
                updContAccessory(EQUIPMENTNO, AccessoryNo);
            }

        }

        /// <summary>
        /// 改變模具狀態 上模使用
        /// </summary>
        private void change_ACC_state(string AccessoryNo, string default_time, int ACLoadTime)
        {
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmsaccstate = new DataTable();
            DataTable dtEmseqpstate = new DataTable();

            sbSQL.Clear();
            sbSQL.Append(" Select a.ACCSerialNo,a.AccessoryState,a.StartTime,a.UserNo,a.Description,a.AccessoryNo,a.AccessoryVersion,a.APPLYTIME,a.ACCUMULATEQTY,a.ACUnLoadTime,b.* ");
            sbSQL.Append(" From tblEMSAccessoryState a, TBLEQPACCESSORYBASIS b ");
            sbSQL.Append(" Where a.AccessoryNo = '" + AccessoryNo + "' And a.AccessoryVersion = (select AccessoryVersion from TBLEQPACCESSORYBASIS where AccessoryNo = '" + AccessoryNo + "' and CURVERSION = 1) ");
            sbSQL.Append(" and a.AccessoryNo = b.AccessoryNo and a.AccessoryVersion = b.AccessoryVersion");

            //檢查是否有資料
            dtEmsaccstate = CurrentService.GetDao().Query(sbSQL.ToString());

            if (dtEmsaccstate.Rows.Count.Equals(0))
                throw new ServiceException(ServiceCode.ParamsValidateException, package_err("tblEMSAccessoryState") + package_err("DATA NOT FOUND"));

            sbSQL.Clear();
            // 20230424 modify by xingl for M#0133684: CHANGETTOOLTIME改为CHANGETOOLTIME
            sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME) ");
            sbSQL.Append("Values('" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + dtEmsaccstate.Rows[0]["AccessoryState"] + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'"+default_time+"','" + dtEmsaccstate.Rows[0]["Description"] + "', ");

            if (!dtEmsaccstate.Rows[0]["APPLYTIME"].Equals(DBNull.Value))
                sbSQL.Append("To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["APPLYTIME"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),");
            else
                sbSQL.Append("'"+default_time+"',");
            // 20220309 modify by 翰鴻 for M#102577：
            if (!dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].Equals(DBNull.Value))
                sbSQL.Append(dtEmsaccstate.Rows[0]["ACCUMULATEQTY"] + "");
            else
                sbSQL.Append("0");

            if (!dtEmsaccstate.Rows[0]["ACUnLoadTime"].Equals(DBNull.Value))
                sbSQL.Append("," + dtEmsaccstate.Rows[0]["ACUnLoadTime"] + ")");
            else
                sbSQL.Append(", 0)");

            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

            // '變更State,現況變更要重新產生一新的SerialNo
            sbSQL.Clear();
            sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = 2,");
            sbSQL.Append(" StartTime = '"+default_time+"' ,");
            sbSQL.Append(" ACCSerialNo ='" + InitACCSerialNo() + "',");
            sbSQL.Append(" UserNo = '" + BaseService._ServiceInfo.account + "',");
            //20220308 modify by 翰鴻 for M#102577
            sbSQL.Append(" Description = '',");
            sbSQL.Append(" ACLoadTime = '" + Convert.ToString(ACLoadTime) + "'");
            sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");

            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

        }
        public void change_ACC_state_auto_InOut(string AccessoryNo, string default_time, int ACLoadTime)
        {
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmsaccstate = new DataTable();
            sbSQL.Append(" Select a.ACCSerialNo,a.AccessoryState,a.StartTime,a.UserNo,a.Description,a.AccessoryNo,a.AccessoryVersion,a.APPLYTIME,a.ACCUMULATEQTY,a.ACUnLoadTime,b.* ");
            sbSQL.Append(" From tblEMSAccessoryState a, TBLEQPACCESSORYBASIS b ");
            sbSQL.Append(" Where a.AccessoryNo = '" + AccessoryNo + "' And a.AccessoryVersion = (select AccessoryVersion from TBLEQPACCESSORYBASIS where AccessoryNo = '" + AccessoryNo + "' and CURVERSION = 1) ");
            sbSQL.Append(" and a.AccessoryNo = b.AccessoryNo and a.AccessoryVersion = b.AccessoryVersion");
            dtEmsaccstate = CurrentService.GetDao().Query(sbSQL.ToString());
            if (dtEmsaccstate.Rows.Count.Equals(0))
                throw new ServiceException(ServiceCode.ParamsValidateException, package_err("tblEMSAccessoryState") + package_err("DATA NOT FOUND"));
            string acc_state = dtEmsaccstate.Rows[0]["AccessoryState"].ToString();
            string apply_time = default_time;
            string acc_umulate_qty = "0";
            if (dtEmsaccstate.Rows[0]["APPLYTIME"].Equals(DBNull.Value) == false)
            {
                apply_time = Convert.ToDateTime(dtEmsaccstate.Rows[0]["APPLYTIME"]).ToString("yyyy-MM-dd HH:mm:ss");
            }
            if (!dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].Equals(DBNull.Value))
            {
                acc_umulate_qty = dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].ToString();
            }
            //20220309 modify by 翰鴻 for M#102577
            string ACUnLoadTime = "0";
            if (!dtEmsaccstate.Rows[0]["ACUnLoadTime"].Equals(DBNull.Value))
            {
                ACUnLoadTime = Convert.ToString(dtEmsaccstate.Rows[0]["ACUnLoadTime"]);
            }
            sbSQL.Clear();
            sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME) ");
            sbSQL.Append("Values('" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + dtEmsaccstate.Rows[0]["AccessoryState"] + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'" + default_time + "','" + dtEmsaccstate.Rows[0]["Description"] + "', '"+ apply_time + "',"+ acc_umulate_qty +"," + ACUnLoadTime +")");
            this.CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
            if (acc_state.Equals("0"))
            {
                List<string> state_list = new List<string>() {"1","2"};
                for(int i = 0;i <state_list.Count;i++)
                {
                    string state = state_list[i];
                    string acc_ser_no = InitACCSerialNo();
                    sbSQL.Clear();
                    sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = "+ state + ",");
                    sbSQL.Append(" StartTime = '" + default_time + "' ,");
                    sbSQL.Append(" ACCSerialNo ='" + acc_ser_no + "',");
                    sbSQL.Append(" UserNo = '" + BaseService._ServiceInfo.account + "',");
                    //20220308 modify by 翰鴻 for M#102577
                    sbSQL.Append(" Description = '',");
                    sbSQL.Append(" ACLoadTime = '" + Convert.ToString(ACLoadTime) + "'");
                    sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    if(i < (state_list.Count-1))
                    {
                        sbSQL.Clear();
                        sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME) ");
                        sbSQL.Append("Values('" + acc_ser_no + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" +state + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'" + default_time + "','" + dtEmsaccstate.Rows[0]["Description"] + "', '" + apply_time + "'," + acc_umulate_qty + "," + ACUnLoadTime + ")");
                        this.CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    }
                }
            }
            else
            {
                sbSQL.Clear();
                sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = 2,");
                sbSQL.Append(" StartTime = '" + default_time + "' ,");
                sbSQL.Append(" ACCSerialNo ='" + InitACCSerialNo() + "',");
                sbSQL.Append(" UserNo = '" + BaseService._ServiceInfo.account + "',");
                //20220308 modify by 翰鴻 for M#102577
                sbSQL.Append(" Description = '',");
                sbSQL.Append(" ACLoadTime = '" + Convert.ToString(ACLoadTime) + "'");
                sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");
                CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
            }
        }

        /// <summary>
        /// 改變模具狀態 下模使用
        /// </summary>
        private void change_ACC_state_for_down(DataRow _DataRow,string default_time, int ACLoadTime)
        {
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmsaccstate = new DataTable();
            DataTable dtEmseqpstate = new DataTable();

            sbSQL.Clear();
            sbSQL.Append(" Select a.ACCSerialNo,a.AccessoryState,a.StartTime,a.UserNo,a.Description,a.AccessoryNo,a.AccessoryVersion,a.APPLYTIME,a.ACCUMULATEQTY,a.ACUnLoadTime,b.* ");
            sbSQL.Append(" From tblEMSAccessoryState a, TBLEQPACCESSORYBASIS b ");
            sbSQL.Append(" Where a.AccessoryNo = '" + _DataRow["AccessoryNo"] + "' And a.AccessoryVersion = (select AccessoryVersion from TBLEQPACCESSORYBASIS where AccessoryNo = '" + _DataRow["AccessoryNo"] + "' and CURVERSION = 1) ");
            sbSQL.Append(" and a.AccessoryNo = b.AccessoryNo and a.AccessoryVersion = b.AccessoryVersion");

            //檢查是否有資料
            dtEmsaccstate = CurrentService.GetDao().Query(sbSQL.ToString());

            if (dtEmsaccstate.Rows.Count.Equals(0))
                throw new ServiceException(ServiceCode.ParamsValidateException, package_err("tblEMSAccessoryState") + package_err("DATA NOT FOUND"));

            sbSQL.Clear();
            sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME) ");
            sbSQL.Append("Values('" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + dtEmsaccstate.Rows[0]["AccessoryState"] + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'"+default_time+ "','" + dtEmsaccstate.Rows[0]["Description"] + "', ");

            if (!dtEmsaccstate.Rows[0]["APPLYTIME"].Equals(DBNull.Value))
                sbSQL.Append("To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["APPLYTIME"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),");
            else
                sbSQL.Append("'"+default_time+ "',");
            // 20220309 modify by 翰鴻 for M#102577：
            if (!dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].Equals(DBNull.Value))
                sbSQL.Append(dtEmsaccstate.Rows[0]["ACCUMULATEQTY"]);
            else
                sbSQL.Append("0");
            if (!dtEmsaccstate.Rows[0]["ACUnLoadTime"].Equals(DBNull.Value))
                sbSQL.Append(", " + dtEmsaccstate.Rows[0]["ACUnLoadTime"] + ")");
            else
                sbSQL.Append(", 0)");

            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

            // '變更State,現況變更要重新產生一新的SerialNo
            sbSQL.Clear();
            sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = 1,");
            sbSQL.Append(" StartTime = '"+default_time+ "',");
            sbSQL.Append(" ACCSerialNo ='" + InitACCSerialNo() + "',");
            sbSQL.Append(" UserNo = '" + BaseService._ServiceInfo.account + "',");
            //20220308 modify by 翰鴻 for M#102577
            sbSQL.Append(" Description = '',");
            sbSQL.Append(" ACLoadTime = '" + Convert.ToString(ACLoadTime) + "'");
            sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");

            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

        }

        public void change_ACC_state_for_down_auto_InOut(DataRow _DataRow, string default_time, int ACLoadTime)
        {
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtEmsaccstate = new DataTable();
            sbSQL.Clear();
            // 20220309 modify by 翰鴻 for M#102577：
            sbSQL.Append(" Select a.ACCSerialNo,a.AccessoryState,a.StartTime,a.UserNo,a.Description,a.AccessoryNo,a.AccessoryVersion,a.APPLYTIME,a.ACCUMULATEQTY, a.ACUnLoadTime,b.* ");
            sbSQL.Append(" From tblEMSAccessoryState a, TBLEQPACCESSORYBASIS b ");
            sbSQL.Append(" Where a.AccessoryNo = '" + _DataRow["AccessoryNo"] + "' And a.AccessoryVersion = (select AccessoryVersion from TBLEQPACCESSORYBASIS where AccessoryNo = '" + _DataRow["AccessoryNo"] + "' and CURVERSION = 1) ");
            sbSQL.Append(" and a.AccessoryNo = b.AccessoryNo and a.AccessoryVersion = b.AccessoryVersion");
            //檢查是否有資料
            dtEmsaccstate = CurrentService.GetDao().Query(sbSQL.ToString());
            if (dtEmsaccstate.Rows.Count.Equals(0))
                throw new ServiceException(ServiceCode.ParamsValidateException, package_err("tblEMSAccessoryState") + package_err("DATA NOT FOUND"));
            string apply_time = default_time;
            string acc_umulate_qty = "0";
            if (dtEmsaccstate.Rows[0]["APPLYTIME"].Equals(DBNull.Value) == false)
            {
                apply_time = Convert.ToDateTime(dtEmsaccstate.Rows[0]["APPLYTIME"]).ToString("yyyy-MM-dd HH:mm:ss");
            }
            if (!dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].Equals(DBNull.Value))
            {
                acc_umulate_qty = dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].ToString();
            }

            sbSQL.Clear();
            // 20220309 modify by 翰鴻 for M#102577：
            string ACUnLoadTime = "0";
            if(!dtEmsaccstate.Rows[0]["ACUnLoadTime"].Equals(DBNull.Value))
            {
                ACUnLoadTime = Convert.ToString( dtEmsaccstate.Rows[0]["ACUnLoadTime"]);
            }
            sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME ) ");
            sbSQL.Append("Values('" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + dtEmsaccstate.Rows[0]["AccessoryState"] + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'" + default_time + "','" + dtEmsaccstate.Rows[0]["Description"] + "', '" + apply_time + "'," + acc_umulate_qty + "," + ACUnLoadTime + ")");
            this.CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
            List<string> state_list = new List<string>() { "1", "0" };
            for(int i = 0;i< state_list.Count;i++)
            {
                string state = state_list[i];
                string acc_ser_no = InitACCSerialNo();
                sbSQL.Clear();
                sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = "+ state + ",");
                sbSQL.Append(" StartTime = '" + default_time + "',");
                sbSQL.Append(" ACCSerialNo ='" + acc_ser_no + "',");
                sbSQL.Append(" UserNo = '" + BaseService._ServiceInfo.account + "',");
                //20220308 modify by 翰鴻 for M#102577
                sbSQL.Append(" Description = '',");
                sbSQL.Append(" ACLoadTime = '" + Convert.ToString( ACLoadTime ) + "'");
                sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");
                CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                if (i < (state_list.Count - 1))
                {
                    sbSQL.Clear();
                    sbSQL.Append("Insert into tblEMSAccessoryStateLog(ACCSerialNo,AccessoryNo,AccessoryVersion,AccessoryState,AccessoryType,UserNo,StartTime,EndTime,Description,APPLYTIME,ACCUMULATEQTY,CHANGETOOLTIME ) ");
                    sbSQL.Append("Values('" + acc_ser_no + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + state + "','" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "', To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),'" + default_time + "','" + dtEmsaccstate.Rows[0]["Description"] + "', '" + apply_time + "'," + acc_umulate_qty + "," + ACUnLoadTime + ")");
                    this.CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
           }
        }
        /// <summary>
        /// 將產生ACC Serial
        /// </summary>
        /// <returns></returns>
        private string InitACCSerialNo()
        {
            string ACCSerialNo = "", strYear, strMonth;
            var strTempDate = new object();
            var SerialNo_ACCSTATELOG = new object();
            var SerialNo_ACCSTATEDATE = new object();
            StringBuilder sbSQL = new StringBuilder();
            int intSerial = 1;
            strYear = DateTime.Now.Year.ToString().Substring(2, 2); //2018 取18
            strMonth = DateTime.Now.Month.ToString("d2");

            if ("oracle".Equals(CurrentService.GetDao().DBType.ToLower()))
            {

                //'1.檢查Sequenct物件是否存在
                string sequenceName = "ACCSTATELOG" + strYear + strMonth;
                sbSQL.Clear();
                sbSQL.Append("Select Object_Name from User_Objects Where Object_Type = 'SEQUENCE' And Object_Name = '" + sequenceName + "'");
                DataTable dtTmp = CurrentService.GetDao().Query(sbSQL.ToString());

                if (dtTmp == null || dtTmp.Rows.Count == 0)
                {
                    //0071379: 模治具上下模出现问题
                    sbSQL.Clear();
                    sbSQL.Append("Create Sequence " + sequenceName + " Increment by 1 " + " Start with 1 " + " MaxValue 99999999 MinValue 0 Cycle Cache 20");

                    //'呼叫執行SQL指令
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                }
                dtTmp.Clear();

                //'2.取得Sequence的流水號
                sbSQL.Clear();
                sbSQL.Append("Select " + sequenceName + ".NextVal as NextValue From Dual");
                dtTmp = CurrentService.GetDao().Query(sbSQL.ToString());

                if (dtTmp != null && dtTmp.Rows.Count > 0) intSerial = Convert.ToInt32(dtTmp.Rows[0]["NextValue"]);
                else throw new ServiceException(ServiceCode.DataAbnormalException, package_err("Get NextVal of sequence object:") + sequenceName + package_err("fail") + " !");
                ;
            }
            else
            {
                sbSQL.Clear();
                sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATEDATE'");
                SerialNo_ACCSTATEDATE = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                //防呆
                if (SerialNo_ACCSTATEDATE == null)
                {
                    //'填入新的日期,格式化存入(ex:0412,因Serial為數值故無法存入0412,故一律前面加上1)
                    sbSQL.Clear();
                    sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATEDATE',1" + strYear + strMonth + ")");
                    //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                    // '月的序號
                    sbSQL.Clear();
                    sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                    SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                    if (SerialNo_ACCSTATELOG == null)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                        //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                        CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                    }
                    else
                    {
                        sbSQL.Clear();
                        sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1 Where FunctionName = 'ACCSTATELOG'");
                        //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                        CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                    }

                    intSerial = 1;
                }
                else
                {
                    strTempDate = SerialNo_ACCSTATEDATE;

                    //'更新日期,格式化存入(ex:041208,因Serial為數值故無法存入041208,故一律前面加上1)
                    sbSQL.Clear();
                    sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1" + strYear + strMonth + " Where FunctionName = 'ACCSTATEDATE'");
                    //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                    // '比較日期

                    if ((strTempDate.ToString()).Equals("1" + strYear + strMonth)) //'同月
                    {
                        // '取出月的序號
                        sbSQL.Clear();
                        sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                        SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());
                        if (SerialNo_ACCSTATELOG == null)
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                            intSerial = 1;
                        }
                        else
                        {
                            // '填入新SerialNo
                            sbSQL.Clear();
                            sbSQL.Append("Update tblSysSerialNo Set SerialNo = " + (Convert.ToInt32(SerialNo_ACCSTATELOG) + 1) + " Where FunctionName = 'ACCSTATELOG'");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                            intSerial = (Convert.ToInt32(SerialNo_ACCSTATELOG) + 1);
                        }
                    }
                    else
                    {
                        //'月的序號
                        sbSQL.Clear();
                        sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                        SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                        if (SerialNo_ACCSTATELOG == null)
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                        }
                        else
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1 Where FunctionName = 'ACCSTATELOG'");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                        }
                        intSerial = 1;
                    }
                }
            }
                            

            // 'ACC Serial No編碼規則
            // '一碼前置字元 +　西元年後兩碼　＋ 兩碼月份 + 七碼流水號
            // '每月流水號歸零，例如S06010000001

            ACCSerialNo = "A" + strYear + strMonth + intSerial.ToString("0000000");
            return ACCSerialNo;
        }

        /// <summary>
        /// 新增 TBLWIPCONT_ACCESSORY 紀錄
        /// </summary>
        /// <param name="_CDO_RequestContent_detail"></param>
        private void AddContAccessory(CDO_RequestContent_detail _CDO_RequestContent_detail)
        {
            StringBuilder sbSQL = new StringBuilder();

            sbSQL.Append("SELECT TP.LOTNO,TP.OPNO,INPUTQTY,TP.LOGGROUPSERIAL, ST.LOTSERIAL ");
            sbSQL.Append("FROM TBLWIPTEMP_EQUIPMENT TP ");
            //20240205 modify by wangzy for M#0156373: 豪中豪：查询模治具历史明细资料表发现，有两笔数据的时间重复，上模下模可以复现该问题
            sbSQL.Append("JOIN TBLWIPLOTSTATE ST ON ST.LOTNO = TP.LOTNO AND (ST.STATUS = 1 OR (ST.STATUS = 2 AND GOSTATUS = 1)) AND ST.CURQTY >0 ");
            sbSQL.Append("WHERE EQUIPMENTNO ='" + _CDO_RequestContent_detail.EQUIPMENTNO + "' ");

            DataTable onEqPLot = CurrentService.GetDao().Query(sbSQL.ToString());
            if (onEqPLot.Rows.Count > 0)
            {
                foreach (DataRow row in onEqPLot.Rows)
                {
                    sbSQL.Clear();
                    sbSQL.Append("INSERT INTO TBLWIPCONT_ACCESSORY(LOTSERIAL,EQUIPMENTNO,ACCESSORYTYPE,ACCESSORYNO,STARTTIME,LOGGROUPSERIAL,USEQTY)");
                    sbSQL.Append("VALUES('" + Convert.ToString(row["LOTSERIAL"]) + "'");
                    sbSQL.Append(",'" + _CDO_RequestContent_detail.EQUIPMENTNO + "'");
                    sbSQL.Append(",'" + _CDO_RequestContent_detail.ACCESSORYTYPE + "'");
                    sbSQL.Append(",'" + _CDO_RequestContent_detail.ACCESSORYNO + "'");
                    sbSQL.Append(",SYSDATE");
                    sbSQL.Append(",'" + Convert.ToString(row["LOGGROUPSERIAL"]) + "', 0 )"); // LOGGROUPSERIAL,USEQTY
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
            }
        }

        /// <summary>
        /// 更新 TBLWIPCONT_ACCESSORY 
        /// </summary>
        /// <param name="_CDO_RequestContent_detail"></param>
        private void updContAccessory(string EQUIPMENTNO, string AccessoryNo)
        {
            StringBuilder sbSQL = new StringBuilder();

            // 取得設備上的生產批 LOGGROUPSERIAL
            sbSQL.Append("SELECT LOGGROUPSERIAL, EQUIPMENTNO ");
            sbSQL.Append("FROM TBLWIPTEMP_EQUIPMENT ");
            sbSQL.Append("WHERE EQUIPMENTNO ='" + EQUIPMENTNO + "' ");

            DataTable onEqPLot = CurrentService.GetDao().Query(sbSQL.ToString());
            if (onEqPLot.Rows.Count > 0)
            {
                foreach (DataRow row in onEqPLot.Rows)
                {
                    sbSQL.Clear();
                    sbSQL.Append(" UPDATE TBLWIPCONT_ACCESSORY");
                    sbSQL.Append(" SET ENDTIME = SYSDATE");
                    sbSQL.Append(" WHERE EQUIPMENTNO = '" + EQUIPMENTNO + "'");
                    sbSQL.Append(" AND LOGGROUPSERIAL = '" + Convert.ToString(row["LOGGROUPSERIAL"]) + "'");
                    sbSQL.Append(" AND ACCESSORYNO = '" + AccessoryNo + "' AND ENDTIME IS NULL ");

                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
            }
        }
        /// <summary>
        /// 判斷是否自動出入庫
        /// </summary>
        /// <returns></returns>
        public bool get_auto_inout_val()
        {
            bool is_auto = false;
            string auto_val = CommonUtilities.GetParameterValue("EQPACCINVAutoInOut");
            if(string.IsNullOrEmpty(auto_val) == false)
            {
                if (auto_val.Equals("Y") || auto_val.Equals("1"))
                    is_auto = true;
            }
            return is_auto;
        }

        /// <summary>
        /// 判斷是否自動下模 未使用
        /// </summary>
        /// <returns></returns>
       /* private bool unload_accessory_from_equipment_auto(string EQUIPMENTNO,string account)
        {
            bool OutData = false;

            OutData = true;
            return OutData;
        }*/

        /// <summary>
        /// 封裝語系
        /// 模組名稱 + errvalue
        /// </summary>
        /// <param name="errvalue"></param>
        /// <returns></returns>
        private string package_err(string errvalue)
        {
            // return CurrentService.GetResource("[%" + CurrentService.GetServiceInfo().service_module + "." + errvalue +
            return CurrentService.GetResource("[%Module_ACC." + errvalue + "%]");
        }

        /// <summary>
        /// 判斷模治具是否已經做過其他功能的狀態異動
        /// </summary>
        /// <param name="accessoryNo">模具編號</param>
        /// <param name="accessoryVersion">模具版本</param>
        /// <param name="accserialNo">模具序號</param>
        /// <returns></returns>
        /// <remarks>
        /// 20210426 Modify by Zeke for 85272: 模具上模報錯：TBLEMSEQPACCSTATE重覆索引 [金名山]
        /// </remarks>
        private bool IsAccSerialStatusChange(string accessoryNo, string accessoryVersion, string accserialNo)
        {
            // 避免前端未準備accserialNo傳入
            if (String.IsNullOrWhiteSpace(accserialNo))
                return false;

            string strAccserialNo = string.Empty;
            StringBuilder sbSQL = new StringBuilder();

            sbSQL.Append(" SELECT ACCSERIALNO FROM TBLEMSACCESSORYSTATE WHERE ACCESSORYNO = '" + accessoryNo + "' AND ACCESSORYVERSION = '" + accessoryVersion + "' ");
            var getAccserialNo = CurrentService.GetDao().Query1RecordColumn(Convert.ToString(sbSQL));

            if (getAccserialNo != null && getAccserialNo != DBNull.Value)
            {
                strAccserialNo = Convert.ToString(getAccserialNo);
            }


            return !accserialNo.ToUpper().Trim().Equals(strAccserialNo.ToUpper().Trim());                
        }
    }
}
